const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const total_config = require('./config');

// 导入 mysql minio 模块
const mysql = require('./db/mysql57');

// 读取配置端口
const port = total_config.port;

// 引入路由
const login_router = require('./router/login');
const city_router = require('./router/city');
const hospital_router = require('./router/hospital');
const user_router = require('./router/user');
const dev_router = require('./router/dev');
const wash_router = require('./router/wash');
const fault_router = require('./router/fault');
const repair_router = require('./router/repair');
const stat_router = require('./router/stat');

// 实例化 express 服务器
const app = express();

// 引入中间件
const coreMiddleware = require('./middleware/coreMiddleware');
const requestId = require('./middleware/requestId');
const recordRequestTime = require('./middleware/recordRequestTime');
const checkUserToken = require('./middleware/checkUserToken');
const power = require('./power/power');

// 使用中间件
// 设置允许跨域请求
app.use(coreMiddleware);     // 允许任何跨域请求
app.use(requestId);          // 记录请求id
app.use(recordRequestTime);  // 记录请求时间

// 静态资源挂载
app.use(express.static(path.join(__dirname, 'public')));

// 设置http请求报文的长度限制为 15M
app.use(bodyParser.json({limit: '15mb'}));
app.use(bodyParser.urlencoded({limit: '15mb', extended: true}));

// 接收 json 请求体
app.use(express.json());

// 路由挂载
app.use('/login', login_router);
app.use(checkUserToken);
app.use('/city', city_router);
app.use('/hospital', hospital_router);
app.use('/user', user_router);
app.use('/dev', dev_router);
app.use('/wash', wash_router);
app.use('/fault', fault_router);
app.use('/repair', repair_router);
app.use('/stat', stat_router);

// TODO: 端口冲突时应该要有更加明显的信息日志提示

// TODO: service层的所有catch都把问题的message进行日志输出 方便后续追查线上问题

// 开启服务器
app.listen(port, async () => {
    // 等待数据库连接
    await mysql.init();
    // 输出服务器启动信息
    console.log(`[ LOG ] 服务器启动于 ${ port } 端口...`);
    console.log(`[ network ] - http://localhost:${ port }`);
    console.log(`[ network ] - http://127.0.0.1:${ port }`);
});